package cn.thornbird.orgsync.helper.token;

import cn.thornbird.orgsync.model.certificate.AppCertificate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;

public abstract class AccessToken<T extends AppCertificate> {

    public static final String ACCESS_TOKEN_KEY = "orgsync:accessToken";

    public static final long EXPIRATION_DELTA = -15000;

    public static final String INVALID_TOKEN_TEXT = "invalidToken,0";

    protected T certificate;

    protected String certificateText;

    public AccessToken(String certificateText) {
        this.certificateText = certificateText;
    }

    public String getToken(RedisTemplate redisTemplate) {
        String accessToken = null;
        String hashKey = certificate.getMd5Key();
        if (redisTemplate != null && redisTemplate.opsForHash().hasKey(ACCESS_TOKEN_KEY, hashKey)) {
            String[] values = ((String) redisTemplate.opsForHash().get(ACCESS_TOKEN_KEY, hashKey)).split(",");
            if (Long.valueOf(values[1]) > System.currentTimeMillis()) {
                accessToken = values[0];
            }
        }
        if (accessToken == null) {
            String token = acquireToken();
            String[] values = token.split(",");
            if (redisTemplate != null) {
                redisTemplate.opsForHash().put(ACCESS_TOKEN_KEY, hashKey, token);
            }
            accessToken = values[0];
        }
        return accessToken;
    }

    public boolean isValidToken(String token) {
        if (!StringUtils.isEmpty(token)) {
            return INVALID_TOKEN_TEXT.split(",")[0].equals(token);
        }
        return false;
    }

    protected abstract String acquireToken();

}
